package com.system.user.controller;

import java.util.List;
import java.util.Map;

import com.system.user.entity.ThresholdEntity;
import com.system.user.entityVO.GasVO;
import com.system.user.entity.UsageEntity;
import com.system.user.entityVO.*;
import com.system.user.service.*;
import com.system.user.weixin.OpenIdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.system.user.entity.UserEntity;
import com.system.common.utils.*;

import static com.system.user.weixin.OpenIdUtil.oauth2GetOpenid;
import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * 账户接口
 *
 * @author HYXK
 * @email null@qq.com
 * @date 2020-03-27 11:55:11
 */
@Api(tags = "账户接口")
@RestController
@RequestMapping("/user")
public class UserController {

    private static String msg = "正常";

    @Autowired
    private UserService userService;

    @Autowired
    private BindService bindService;

    @Autowired
    private ThresholdService thresholdService;

    @Autowired
    private WaterService waterService;

    @Autowired
    private LightingService lightingService;

    @Autowired
    private GasService gasService;

    @Autowired
    private UsageService usageService;

    /**
     * 查找所有信息
     *
     * @return
     */
    @ApiOperation("查找所有信息")
    @RequestMapping(value = "/list", method = GET)
    public R list() {
        List<UserEntity> page = userService.findAll();

        return R.ok().put("page", page);
    }

    /**
     * 模糊查询
     *
     * @return
     */
    @ApiOperation("模糊查询")
    @RequestMapping(value = "/listByParam", method = POST)
    public R listByParam(@RequestBody(required = false) Map<String, Object> map) {
        String param = map.get("param") != null ? map.get("param").toString() : null;
        List<UserEntity> page = userService.findAll();

        return R.ok().put("page", page);
    }

    /**
     * 管理员添加
     *
     * @param map
     * @return
     */
    @ApiOperation("管理员添加")
    @RequestMapping(value = "adminRegister", method = POST)
    public R adminRegister(@RequestBody Map<String, Object> map) {
        try {
            String username = map.get("username").toString();
            String password = map.get("password").toString();
            boolean is_success = userService.adminRegister(username, password);
            if (is_success) {
                return R.ok("添加成功！");
            }
            return R.error("添加失败！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }

    }

    /**
     * 小程序登录，若用户不存在自动注册
     *
     * @param map
     * @return
     */
    @ApiOperation("小程序登录，若用户不存在自动注册，参数{\"code\":1}")
    @RequestMapping(value = "weiXinLogin", method = POST)
    public R weiXinRegister(@RequestBody Map<String, Object> map) {
        try {
            String code = map.get("code").toString();
            String openid = oauth2GetOpenid(code);
            UserEntity user = userService.weiXinLogin(openid);
            if (user != null) {
                return R.ok("登录成功！").put("user", user);
            }
            return R.error("登录失败！").put("user", null);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }

    }

    /**
     * 管理员登录
     *
     * @param map
     * @return
     */
    @ApiOperation("管理员登录")
    @RequestMapping(value = "adminLogin", method = POST)
    public R adminLogin(@RequestBody Map<String, Object> map) {
        try {
            String username = map.get("username").toString();
            String password = map.get("password").toString();
            UserEntity user = userService.adminLogin(username, password);
            if (user != null && user.getState().equals("0")) {
                user.setPassword("*********");
                user.setState(null);
                return R.ok("登录成功！").put("user", user);
            }
            return R.error("登录失败！").put("user", user);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }

    }

    /**
     * 小程序主页查找本人绑定的点水表最新的一条数据
     *
     * @param map
     * @return
     */
    @ApiOperation("小程序主页查找本人绑定的点水表最新的一条数据，参数{\"uid\":1}")
    @RequestMapping(value = "findAllWatch", method = POST)
    public R findAllWatch(@RequestBody Map<String, Object> map) {
        try {
            Integer uId = Integer.valueOf(map.get("uid").toString());
            if (uId > 0) {
                List<WaterVO> waterVOS = waterService.findWaterVOByUId(uId, null);
                List<LightingVO> lightingVOS = lightingService.findAllLight(uId, null);
                List<GasVO> gasVOS = gasService.selectByUid(uId, null);
                return R.ok().put("waterList", waterVOS).put("lightingList", lightingVOS).put("gasList", gasVOS);
            }
            return R.error();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    /**
     * 后台查找绑定信息
     *
     * @param map
     * @return
     */
    @ApiOperation("后台查找绑定信息，参数{\"uid\":1}")
    @RequestMapping(value = "queryAllWatch", method = POST)
    public R queryAllWatch(@RequestBody Map<String, Object> map) {
        try {
            Integer uId = Integer.valueOf(map.get("uid").toString());
            if (uId > 0) {
                List<WatchVO> watchVOS = userService.queryAllWatch(uId);
                return R.ok().put("watchList", watchVOS);
            }
            return R.error();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }

    }

    /**
     * 根据表编号查找所有历史数据，w表示水表，l表示电表
     *
     * @param map
     * @return
     */
    @ApiOperation("根据bNumber查找表所有数据，参数{\"bNumber\":w1}")
    @RequestMapping(value = "/queryAllByBNumber", method = RequestMethod.POST)
    public R queryAllByBNumber(@RequestBody Map<String, Object> map) {
        try {
            String bNumber = map.get("bNumber").toString();
            String createTime = map.get("createTime").toString();
            if (bNumber.indexOf("w") > -1){
                List<WaterVO> waterVOS = waterService.findAllByBNumber(bNumber, createTime);
                return R.ok().put("list", waterVOS);
            } else if (bNumber.indexOf("l") > -1) {
                List<LightingVO> lightingVOS = lightingService.findAllByBNumber(bNumber, createTime);
                return R.ok().put("list", lightingVOS);
            }
            return R.error("查找失败！");
        } catch (Exception e) {
            return R.error("服务器异常！");
        }

    }

    /**
     * 绑定表信息
     *
     * @param map
     * @return
     */
    @ApiOperation("绑定表信息，参数{\"uid\":1, \"bNumber\":\"w1\"}")
    @RequestMapping(value = "bindMsg", method = POST)
    public R bindMsg(@RequestBody Map<String, Object> map) {
        try {
            Integer uid = Integer.valueOf(map.get("uid").toString());
            String bNumber = map.get("bNumber").toString();
            if (uid != null && bNumber != null) {
                if (bindService.add(uid, bNumber)) {
                    return R.ok("绑定成功！");
                }
            }
            return R.error("绑定失败，信息不正确！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }

    }

    /**
     * 删除绑定表信息
     *
     * @param map
     * @return
     */
    @ApiOperation("删除绑定表信息，参数{\"uid\":1, \"bNumber\":\"w1\"}")
    @RequestMapping(value = "deleteBindMsg", method = POST)
    public R deleteBindMsg(@RequestBody Map<String, Object> map) {
        try {
            Integer uid = Integer.valueOf(map.get("uid").toString());
            String bNumber = map.get("bNumber").toString();
            if (uid != null && bNumber != null) {
                if (bindService.deleteByUidAndBNumber(uid, bNumber)) {
                    return R.ok("解绑成功！");
                }
            }
            return R.error("解绑失败！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    /**
     * 查找阈值
     *
     * @param map
     * @return
     */
    @ApiOperation("查找阈值，参数{\"uid\":1}")
    @RequestMapping(value = "findThreshold", method = POST)
    public R findThreshold(@RequestBody Map<String, Object> map) {
        try {
            Integer uid = Integer.valueOf(map.get("uid").toString());
            List<ThresholdEntity> thresholdEntities = thresholdService.selectByBNumber(uid);
            return R.ok("查询成功！").put("list", thresholdEntities);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    /**
     * 更新阈值
     *
     * @param threshold
     * @return
     */
    @ApiOperation("更新阈值")
    @RequestMapping(value = "updateThreshold", method = POST)
    public R updateThreshold(@RequestBody ThresholdEntity threshold) {
        try {
            boolean is_success = thresholdService.update(threshold);
            if (is_success) {
                return R.ok("修改成功！");
            }
            return R.error("修改失败！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }

    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @ApiOperation("修改用户信息")
    @RequestMapping(value = "updateUser", method = POST)
    public R updateUser(@RequestBody UserEntity user) {
        try {
            if (userService.updateUser(user)) {
                return R.ok("修改成功！");
            }
            return R.error("修改失败！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    @ApiOperation("删除用户信息")
    @RequestMapping(value = "deleteUser", method = POST)
    public R deleteUser(@RequestParam("id") Integer id) {
        try {
            if (userService.deleteUser(id)) {
                return R.ok("删除成功！");
            }
            return R.error("删除失败！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    @ApiOperation("根据表编号或时间查找")
    @RequestMapping(value = "findUsageByParam", method = POST)
    public R findUsageByParam(@RequestBody UsageParamVO paramVO) {
        try {
            List<UsageEntity> list = usageService.findByParam(paramVO);
            return R.ok("查找成功！").put("list", list);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    @ApiOperation("查找未绑定的表")
    @RequestMapping(value = "findOtherWatch", method = POST)
    public R findOtherWatch(@RequestBody WatchVO watchVO) {
        try {
            List<WatchVO> list = userService.findOtherWatch(watchVO);
            return R.ok("查找成功！").put("list", list);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

    @ApiOperation("根据编号查找阈值")
    @RequestMapping(value = "findMax", method = POST)
    public R findMax(@RequestBody Map<String, Object> map) {
        try {
            String bNumber = map.get("bNumber").toString();
            Double list = thresholdService.findMax(bNumber);
            return R.ok("查找成功！").put("max", list);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error("服务器异常！");
        }
    }

}
